package dk.eclipse.android.badassapp.weapon;

import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import dk.eclipse.android.badassapp.R;
import dk.eclipse.android.badassapp.helper.SoundHelper;
import dk.eclipse.android.badassapp.helper.VibratorHelper;
import dk.eclipse.android.badassapp.preferences.PreferenceHelper;
import dk.eclipse.android.badassapp.widget.WeaponWidget;

/**
 * This class presents the user interface for the weapon tab.
 * 
 * @author Ronni Kahalani (eclipse.dk)
 * 
 */
public class WeaponActivity extends Activity {
	/**
	 * Tag used for logging information.
	 */
	private static final String LOG_TAG = WeaponActivity.class
			.getSimpleName();
	/**
	 * The list of weapons.
	 */
	private List<Weapon> weapons = WeaponHelper.getWeapons();
	/**
	 * The selected weapon image place holder.
	 */
	private ImageView imageView;
	/**
	 * The selected weapon title place holder.
	 */
	private TextView weaponTitleTextView;
	/**
	 * The selected weapon description place holder.
	 */
	private TextView weaponDescTextView;
	/**
	 * The gallery place holder.
	 */
	private Gallery gallery;
	/**
	 * The current weapon index.
	 */
	private int currentWeaponIndex = 0;
	/**
	 * The currently selected weapon.
	 */
	private Weapon selectedWeapon;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_LEFT_ICON);
		setContentView(R.layout.tab_weapon);
		setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
				R.drawable.ic_app);

		gallery = (Gallery) findViewById(R.id.weaponGallery);
		gallery.setAdapter(new ImageAdapter(this));
		gallery.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index,
					long arg3) {
				selectWeapon(index);
				tellWidgetWeaponChanged();
			}
		});

		imageView = (ImageView) findViewById(R.id.selectedWeaponImage);
		imageView.setScaleType(ImageView.ScaleType.FIT_XY);
		imageView.setBackgroundResource(R.drawable.weapon_background);
		imageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				int resourceId = weapons.get(currentWeaponIndex).getSoundId();

				long[] vibration = new long[(currentWeaponIndex + 1) * 2];

				for (int index = 0; (index + 1) < vibration.length; index += 2) {
					vibration[index] = 100;
					vibration[index + 1] = 100;
				}

				VibratorHelper.vibrate(getApplicationContext(), vibration);
				SoundHelper.playSound(getApplicationContext(), resourceId,
						false);
			}
		});

		// Handle long clicks and show dialog to set weapon image as wall paper.
		imageView.setOnLongClickListener(new View.OnLongClickListener() {

			/*
			 * (non-Javadoc)
			 * 
			 * @see
			 * android.view.View.OnLongClickListener#onLongClick(android.view
			 * .View)
			 */
			public boolean onLongClick(View v) {

				AlertDialog dialog = new AlertDialog.Builder(
						WeaponActivity.this).create();
				dialog.setTitle("Confirmation");
				dialog
						.setMessage("Do you want to set this image as wallpaper?");
				dialog.setIcon(R.drawable.ic_app);

				dialog.setButton("Yes", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {

						Bitmap bitmap = BitmapFactory.decodeResource(
								getResources(), selectedWeapon.getImageId());

						try {
							WeaponActivity.this.setWallpaper(bitmap);
							Log.d(LOG_TAG, "Wallpaper set");
						} catch (IOException e) {
							Log.d(LOG_TAG, "Failed to set wallpaper");
							e.printStackTrace();
						}

					}
				});

				dialog.show();
				return true;
			}
		});

		weaponTitleTextView = (TextView) findViewById(R.id.weaponTitleTextView);
		weaponDescTextView = (TextView) findViewById(R.id.weaponDescTextView);

		updateWeaponSelection();
	}

	private void updateWeaponSelection() {
		currentWeaponIndex = PreferenceHelper
				.getPreferredWeapon(getApplicationContext());
		gallery.setSelection(currentWeaponIndex);
		selectWeapon(currentWeaponIndex);
	}

	/**
	 * Checks to see if an intent is available.
	 * 
	 * @param context
	 * @param action
	 * @return true if the intent is available (has at least one handler)
	 */
	public boolean isIntentAvailable(Context context, String action) {
		final PackageManager packageManager = context.getPackageManager();
		final Intent intent = new Intent(action);
		List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(
				intent, PackageManager.MATCH_DEFAULT_ONLY);
		if (resolveInfo.size() > 0) {
			return true;
		}
		return false;
	}

	/**
	 * Tell our HOME-screen weapon widget of the weapon change.
	 */
	protected void tellWidgetWeaponChanged() {

		// We don't need to tell which weapon the user has selected, because the
		// widget reads the "preferredWeapon" preference, that we have just set
		// on the previous line.

		PendingIntent intent = PendingIntent.getBroadcast(
				getApplicationContext(), 0, new Intent(
						WeaponWidget.ACTION_WEAPON_CHANGED), 0);

		try {
			// Tell the weapon widget. If the intent is not handled (because
			// it has not been added to the HOME-screen), we will be
			// thrown an android.content.ActivityNotFoundException, so we have to
			// handle that.
			try {
				intent.send();
			} catch (CanceledException e) {
				e.printStackTrace();
			}

		} catch (ActivityNotFoundException e) {
			// Ignore, the weapon widget might not have been added to the
			// "HOME-screen".
		}

	}

	/**
	 * Selects a weapon via an index into the weapon list.
	 * 
	 * @param index
	 */
	protected void selectWeapon(int index) {
		currentWeaponIndex = index;
		selectedWeapon = weapons.get(index);

		imageView.setImageResource(selectedWeapon.getImageId());
		weaponTitleTextView.setText(selectedWeapon.getName());
		weaponDescTextView.setText(selectedWeapon.getDesc());

		// Let's tell our weapon widget that the selected / preferred weapon has
		// changed, so the widget can update it's image of the preferred weapon.
		PreferenceHelper.setPreferredWeapon(getApplicationContext(), index);

	}

	/**
	 * @author Ronni Kahalani (eclipse.dk)
	 * 
	 */
	public class ImageAdapter extends BaseAdapter {

		/**
		 * The current context.
		 */
		private Context context;
		/**
		 * The background image for the widget.
		 */
		private int imageBackground;

		/**
		 * @param context
		 */
		public ImageAdapter(Context context) {
			this.context = context;

			// Get the styled attributes for the gallery background.
			TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
			imageBackground = ta.getResourceId(
					R.styleable.Gallery1_android_galleryItemBackground, 1);

			// Clean up the typed array.
			ta.recycle();
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getCount()
		 */
		@Override
		public int getCount() {
			return weapons.size();
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getItem(int)
		 */
		@Override
		public Object getItem(int index) {
			return index;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getItemId(int)
		 */
		@Override
		public long getItemId(int index) {
			return index;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.Adapter#getView(int, android.view.View,
		 * android.view.ViewGroup)
		 */
		@Override
		public View getView(int index, View view, ViewGroup viewGroup) {
			// Draw every item in the gallery bar.
			ImageView iv = new ImageView(context);
			iv.setImageResource(weapons.get(index).getImageId());
			iv.setScaleType(ImageView.ScaleType.FIT_XY);
			iv.setLayoutParams(new Gallery.LayoutParams(250, 220));
			iv.setBackgroundResource(imageBackground);
			return iv;
		}
	}
	
	@Override
	protected void onResume() {
			super.onResume();
			updateWeaponSelection();
	}
}